/**   
* @Title: ChildStateJobTimerAIStempImpl.java 
* @Package cn.com.commons.quartzframe.job 
* @Description: 执行子任务的执行器实现
* @author chenmin-ds   
* @version V1.0   
*/ 


package com.gomeplus.commons.quartz.job;

import java.util.Arrays;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.StatefulJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gomeplus.commons.quartz.cache.QuartzTaskConfigCache;
import com.gomeplus.commons.quartz.task.SpartITask;
import com.gomeplus.frame.factory.SpringBeanFactory;

/** 
 * @ClassName: ChildStateJobTimerAIStempImpl 
 * @Description: 执行子任务的执行器实现
 * @author chenmin-ds 
 */

@SuppressWarnings("deprecation")
public class ChildStateJobTimerAIStempImpl implements StatefulJob {

	private Logger logger = LoggerFactory.getLogger("ChildStateJobTimerAIStempImpl");
	
	/* (非 Javadoc) 
	 * <p>Title: execute</p> 
	 * <p>Description: </p> 
	 * @param context
	 * @throws JobExecutionException 
	 * @see org.quartz.Job#execute(org.quartz.JobExecutionContext) 
	 */
	@Override
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void execute(JobExecutionContext context) throws JobExecutionException {
		JSONObject obj = (JSONObject) context.getJobDetail().getJobDataMap().get("TaskBasicConfig");
		try {
			String taskId = context.getJobDetail().getKey().getName();
			JSONObject objNew = JSONObject.fromObject(obj);//重克隆防止并发
			String[] partAndModeValues = QuartzTaskConfigCache.getTaskPart(taskId);
			if(null != partAndModeValues && partAndModeValues.length >0){
				objNew.put("modeValue",partAndModeValues[0]);
				objNew.put("partValue", JSONArray.fromObject(partAndModeValues[1].split(",")));
				//logger.info("串行分片taskName={},partValue={}" ,taskId,	objNew.getJSONArray("partValue").toString());
			}
			Object objIStep = SpringBeanFactory.getBean(objNew.getString("businessObjName").trim());
			if(null == objIStep){
				logger.info("没有找到可执行的任务对象，任务名称【{}】，任务对象名称【{}】" , objNew.getString("taskName"),objNew.getString("businessInfo"));
			}else{
				SpartITask istep = (SpartITask) objIStep;
				List<Object> list = istep.queryTaskInfo(objNew);
				if (list != null) {
					for (Object temp : list) {
						if(istep.spart(temp,objNew)) {
							istep.runTask(temp);
						}
					}
					istep.editTaskInfo(list);
					QuartzTaskConfigCache.setTaskRunLogCount(taskId, list.size());
					list.clear();
				} else {
					QuartzTaskConfigCache.setTaskRunLogCount(taskId, 0);
					logger.info("没有查询到需要执行的记录，任务对象名称【{}】，任务参数【{}】" , objNew.getString("taskName"), objNew.getString("businessInfo"));
				}
			}
		} catch (Exception e) {
			logger.error("任务执行异常：" + obj.getString("taskNo"), e);
		}
	}

}
